/*
 *  Project: 
 *  Author: Paweł Świtalla
 *  Email: swit3k@gmail.com
 *  Date: 2011-07-30, 13:47:35
 * 
 */

// Tabs switching
var App = {
  contentContainer: ".cContent",
  tabCookie: "currentTabCookie",
  errorStart: "&nbsp;&nbsp;<span id='error' style='color:red'>",
  errorEnd: "</span>",
  openedWindows: new Array(),
  
  // Logging levels: error, info
  logInConsole: new Object({ error: true }),
  
  reportError:
    function(message){
      if(message != undefined){
        console.log("Error: "+ message +" on "+ name +"\n");
      }
      else console.log("Error occured.");
    },
  showAjaxLoader:
    function(object){
      $(object).html('<div class="ajaxLoader"><img src="/images/icons/ajax-loader.gif"/></div>').hide().fadeIn('200');
    },
  hideAjaxLoader:
    function(object){
      $(object+ '> .ajaxLoader').fadeOut('200').remove();
    },
  ajaxRequest:
    function(targetUrl, dataTarget, returnData, dataToSend){
      if(dataTarget != undefined)
        {
          $.ajax({
            url: targetUrl,
            success: function(data){
              App.hideAjaxLoader(dataTarget);
              $(dataTarget).html(data).hide().slideDown('200');
            },
            error: function(object, status, error){
              $(dataTarget).html("Wystąpił błąd !<br /><b>Typ błędu: </b>"+ status +"<br /><b>Wyjątek: </b>"+ error.message)
              if(App.logInConsole['error']) console.log("Error: "+ error.message +"\n");
            },
            complete: function(object, status){
              App.bindEvents();
              if(App.logInConsole['info']) console.log("AJAX Request:\n\tFrom: "+ targetUrl +"\n\tLoaded to: '"+ dataTarget +"'\n");
            }
          })
        }
      else if(returnData != undefined || dataToSend != undefined)
        {
          $.ajax({
            type: 'POST',
            url: targetUrl,
            data: dataToSend,
            success: function(data){
              if(returnData != undefined) returnData(data);
            }
          })
        }
    },
  tabSelect:
    function(tabName){
      var name = "a[href=#" + tabName + "]";
      $(".cTabs ul li.active").removeClass().addClass("inactive");
      $(name).parent().removeClass().addClass("active");
      var link = $(name).parent().children("a").attr("href");
      if(link != undefined){
        var id = $(name).parent().children("a").attr("href").split("#")[1];
        $(".cIcons > div[id].active").removeClass().addClass("inactive");
        $(".cIcons > div[id=" + id + "]").removeClass().addClass("active");
      }
    },
  bindEvents:
    function(){
      // Main tabs click event
      $(".cTabs ul li").bind("click", function(){
        App.extraContent = false;
        $(".cTabs ul li.active").removeClass().addClass("inactive");
        $(this).removeClass().addClass("active");
        var id = $(this).children("a").attr("href").split("#")[1];
        $(".cIcons > div[id].active").removeClass().addClass("inactive");
        $(".cIcons > div[id=" + id + "]").removeClass().addClass("active");
        document.cookie = App.tabCookie + "=" + id + "; path=/";
        //$('.cInfo p#module + span').html($(this).children('a').children());
      });
      
      // Icons on Ribbon click event
      $(".cIcon a[onclick!='App.loadWindow']").bind("click", function(){
        App.Table.extraContent = new Array();  
      });
      
      // Settings tabs events
      $(".sComponentTabs a .sTab").bind("click", function(){
        if($(".sActiveTab") != $(this)){
          $(".sActiveTab").removeClass("sActiveTab");
          $(this).addClass("sActiveTab");
          App.Table.extraContent = new Array();
        }
      });
    },
  constructor:
    $(function(){
      // Bindings
      App.bindEvents();
      App.openedWindows.push(window);
      
      $.ajaxSetup({
        error: function(object, status, error){
          if(App.logInConsole['error']) console.log("Error: "+ error.message +"\nType: "+ status +"\n");
        },
        complete: function(object, status){
          if(App.logInConsole['info']) console.log("AJAX Request: "+ status);
        }
      });
      
      var name = App.tabCookie + "=";
      var ca = document.cookie.split(';');
      var cookieValue = "";
      for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(name) == 0) cookieValue = c.substring(name.length,c.length);
      }
      if(cookieValue) App.tabSelect(cookieValue);
    }),
  loadContent:
    function(targetUrl, selector){
      var target;
      if(selector === undefined){
        target = App.contentContainer;
      }
      else target = selector;
      App.showAjaxLoader(target);
      App.ajaxRequest(targetUrl, target);
    },
  /*loadWindow:
    function(targetUrl, windowUrl){
      var newWindow = window.open(windowUrl, '', 'width=300, height=300');
      $(newWindow.document).ready(function(){
      App.ajaxRequest(targetUrl, this);
      newWindow.focus();
      });
    },*/
  loadWindow:
    function(windowUrl, width, height){
      if(width == undefined) width = 600;
      if(height == undefined) height = 400;
      var newWindow = window.open(windowUrl, '', 'width='+width+', height='+height+', location=no');
      App.openedWindows.push(newWindow);
      newWindow.focus();
    },
  unloadWindow:
    function(){
      window.close();
    },
  Form: {
    submitWithAjax: true,
    storedForm: undefined,
    submit:
      function(formId, isAjax, refresh){
        function validate(t){
          params = App.Tools.parseParams(t);
          if(params['error'] == undefined && params['location'] != undefined){
            if(window.location != undefined && refresh == undefined){
              window.location = params['location'];
            }
          }
          else if(refresh == true) window.location.reload();
          else if(refresh != undefined) window.location = refresh;
          else if(params['error'] != undefined) alert(params['error']);
          else App.reportError(t);
        }
        
        function data(d){
          var data = '';
          for(i in d){
            if(d[i].type == 'checkbox' && d[i].disabled == false){
              data += d[i].name + '=' + d[i].checked+ '&';
            }
            else if(d[i].type == 'select-multiple' && d[i].disabled == false){
              for(var j = 0; j < d[i].options.length; j++){
                if(d[i].options[j].selected) data += d[i].name + '=' + d[i].options[j].value+ '&';
              }
            }
            else if(d[i].type == 'button')
            {
              continue;
            }
            else if(d[i].disabled == false)
            {
              data += d[i].name + '=' + d[i].value+ '&';
            }
          }
          return data;
        }
        
        if(formId == undefined){
          if(isAjax && App.Form.submitWithAjax){
            
          }
          else document.forms[0].submit();
        }
        else{
          if(isAjax && App.Form.submitWithAjax){
            url = $('form#'+formId).attr('action');
            elements = $('form#'+formId).find('input, select').toArray();
            App.ajaxRequest(url, undefined, validate, data(elements));
          }
          else document.forms[formId].submit();
        }
      },
    switchAndSubmit:
      function(formId, isAjax, refresh){
        if(createItemUrl != ''){
          $('form#'+formId).prop('action', createItemUrl);
          $('form#'+formId).find('input[type=hidden][id]').remove();
          $('form#'+formId).find('input[type=hidden][name=sf_method]').prop('value', 'post');
          App.Form.submit(formId, isAjax, refresh);
        }
        else alert("Operacja niedozwolona. Edytuj w kategorii bazowej.");
      },
    deleteChecked:
      function(formId, listName){
        inputs = $('input[type=checkbox][name^='+listName+']:checked');
        if(inputs.length){
          if(confirm('Ilość pozycji do usunięcia: '+ inputs.length +'\nChcesz kontynuwać?')){
            document.forms[formId].submit();
          }
        }
        else alert('Nie zaznaczono żadnego elementu.');
      },
    store:
      function(formId){
        var elements = $('form#'+formId).find("tr#extra th+td").children("input[type!=hidden], select");
        if(elements.length > 0){
          App.Form.storedForm = new Array();
          for(i in elements){
            switch(elements[i].type){
              case "select-one" :
              case "text" : {
                  App.Form.storedForm.push({
                    type: elements[i].type,
                    id: elements[i].id,
                    value: elements[i].value
                  });
                  break;
              }
              case "select-multiple" : {
                  var options = new Array();
                  for(var j = 0; j < elements[i].length; j++){
                    if(elements[i].options[j].selected) options.push(elements[i].options[j]);
                  }
                  App.Form.storedForm.push({
                    type: elements[i].type,
                    id: elements[i].id,
                    options: options
                  });
                  break;
              }
              case "checkbox" : {
                  App.Form.storedForm.push({
                    type: elements[i].type,
                    id: elements[i].id,
                    checked: elements[i].checked
                  });
                  break;
              }
            }
          }
        }
        else App.reportError();
      },
    restore:
      function(formId){
        if(App.Form.storedForm != undefined){
          var elements = $('form#'+formId).find("tr#extra th+td").children("input[type!=hidden], select");
          for(i in App.Form.storedForm){
            id = App.Form.storedForm[i].id;
            type = App.Form.storedForm[i].type;
            for(j in elements){
              if(id == elements[j].id){
                switch(type){
                  case "select-one" :
                  case "text" : {
                      $(elements[j]).prop("value", App.Form.storedForm[i].value);
                      break;
                  }
                  case "select-multiple" : {
                      for(k in App.Form.storedForm[i].options){
                        var index = App.Form.storedForm[i].options[k];
                        elements[j].options[index].selected = true;
                      }
                      break;
                  }
                  case "checkbox" : {
                      if(App.Form.storedForm[i].checked) $(elements[j]).prop("checked", "true");
                      break;
                  }
                }
              }
            }
          }
        }
        else App.reportError();
      },
    updateAttribute:
      function(selector, attribute, value){
        if((selector && attribute && value) != undefined){
          $(selector).prop(attribute, value);
        }
      },
    validateMultiSelects:
      function(formId, callback){
        var elements = $('#'+formId).find("tr[id] td").children("select");
        var leave = [];
        for(var i = 0; i < elements.length; i++){
          var flag = true;
          var add = false;
          for(var x in leave){
            if(leave[x] == i) flag = false;
          }
          if(flag){
            var sum = parseInt($(elements[i]).closest("td").next("td").children("input").prop('value'));
            var value = $(elements[i]).prop('value');
            for(var j = 0; j < elements.length; j++){
              if(value == $(elements[j]).prop('value') && j != i){
                leave.push(j);
                var inputValue = $(elements[j]).closest("td").next("td").children("input").prop('value');
                $(elements[j]).closest("td").next("td").children("input").attr('disabled', 'disabled');
                $(elements[j]).closest("td").next("td").children("input").prop('value', '');
//                $(elements[j]).attr('disabled', 'disabled');
                $(elements[j]).closest("tr").remove();
                sum += parseInt(inputValue);
                add = true;
              }
            }
          }
          if(add) $(elements[i]).closest("td").next("td").children("input").prop('value', sum);
        }
        if(callback !== undefined) callback();
        return true;
      },
    validateLength:
      function(elements, minLength, maxLength, callback){
        var valid = true;
        var intPatern = /^[0-9]+$/;
        $('span[id=error]').remove();
        elements = $(elements);
        for(var i = 0; i < elements.length; i++){
          value = $(elements[i]).prop('value');
          if(value == ""){
            $(elements[i]).after(App.errorStart + "Podaj wartość" + App.errorEnd);
            valid = false;
          }
          else if(!intPatern.test(value)){
            $(elements[i]).after(App.errorStart + "Podaj liczbę" + App.errorEnd);
            valid = false;
          }
          else if(value.length < minLength){
            $(elements[i]).after(App.errorStart + "Min. " + minLength + " znaków." + App.errorEnd);
            valid = false;
          }
          else if(value.length > maxLength){
            $(elements[i]).after(App.errorStart + "Max. " + maxLength + " znaków." + App.errorEnd);
            valid = false;
          }
          else if($(elements[i]).next('span[id=error]')){
            $(elements[i]).next('span[id=error]').remove();
          }
        }
        if(callback !== undefined) callback();
        if(valid) return true;
        else return false;
      },
    validateData:
      function(source, target, callback){
        if(typeof source == "string" && typeof target == "string") return source === target;
        else if(typeof source == "object" && typeof target == "object"){
          if(source.length == target.length){
            var flag = true;
            for(var i in source)
            {
              if(source[i] != target[i]) flag = false;
            }
            if(callback !== undefined) callback();
            return flag;
          }
          else{
            if(callback !== undefined) callback();
            return false;
          }
        }
        else{
          if(callback !== undefined) callback();
          return false;
        }
      },
    validateQuantity:
      function(object, keysPattern, callback){
        var array = eval('(' + object.responseText + ')');
        var keys = $(keysPattern);
        function removeErrors(){
          for(var j = 0; j < keys.length; j++){
            isInArray = false;
            emptyArray = true;
            if(array.length == undefined){
              emptyArray = false;
              for(var x in array){
                if($(keys[j]).prop("value") == x){
                  isInArray = true;
                }
              }
            }
            if((!isInArray || emptyArray) && $(keys[j]).parent("td").next("td").children("span[id=error]").length){
              $(keys[j]).parent("td").next("td").children("span[id=error]").html("");
            }
          }
        }
        removeErrors();
        if(array.length == undefined){
          for(var i in array){
            for(var j = 0; j < keys.length; j++){
              if($(keys[j]).prop("value") == i){
                if($(keys[j]).parent("td").next("td").children("span[id=error]").length) $(keys[j]).parent("td").next("td").children("span[id=error]").html(App.errorStart +"Dostępne: "+ array[i].quantity +" ["+ array[i].unit +"]"+ App.errorEnd);
                else $(keys[j]).parent("td").next("td").children("input[type=text]").after(App.errorStart +"Dostępne: "+ array[i].quantity +" ["+ array[i].unit +"]"+ App.errorEnd);
              }
            }
          }
          return false;
        }
        else{
          if(callback != undefined) eval(callback);
          return true;
        }
      },
    validateWZ:
      function(keysPattern, valuesPattern, url){
        if(App.Form.validateLength('input[id*=items_list_values]', 1)){
          function submit(){
            wzJHR = App.Form.checkItemsQuantity(keysPattern,
                                                valuesPattern,
                                                url,
                                                "App.Form.submit('wzForm', true)"
                                                );
          }
          App.Form.validateMultiSelects('wzForm', submit);
        }
      },
    validateYawalXls:
      function(){
        var elements = $('td input[type="hidden"]');
        var ids = [];
        var old = [];
        
        for(var i = 0; i < elements.length; i++)
        {
          var string = $(elements[i]).prop("name");
          var id = string.split("[")[1].split("]")[0];
          
          var value = parseInt($(elements[i]).prop("value"));
          
          if(ids[id] !== undefined) ids[id] += value;
          else ids[id] = value;
        }
        
        for(var i = 0; i < elements.length; i++)
        {
          var string = $(elements[i]).prop("name");
          var id = string.split("[")[1].split("]")[0];
          
          if(old[id] === undefined)
          {
            $(elements[i]).prop("value", ids[id]);
            old[id] = 1;
          }
          else if(old[id] === 1)
          {
            $(elements[i]).remove();
          }
        }
      },
    toggleDisable:
      function(inputType, namePattern){
        var input = $(inputType+"[name*="+namePattern+"]")
        if(input.prop("disabled") == false) input.prop("disabled", "disabled");
        else if(input.prop("disabled") == true) input.prop("disabled", "");
      },
    checkItemsQuantity:
      function(keysPattern, valuesPattern, url, callback){
        var keys = $(keysPattern);
        var values = $(valuesPattern);
        var string = "";
        if(keys.length === values.length){
          for(var i = 0; i < keys.length; i++)
          {
            if($(values[i]).prop("value")) string += "items[" + [parseInt($(keys[i]).prop("value"))] +"]="+ $(values[i]).prop("value") +"&";
          }
          
          var jhr = $.ajax({
            type: 'POST',
            url: url,
            data: string,
            complete: function(object, status){
              App.Form.validateQuantity(object, keysPattern, callback);
            }
          });
          return jhr;
        }
        else return false;
      }
  },
  Table: {
    checkedAll: new Array(),
    extraContent: new Array(),
    standardContent: undefined,
    lastAttachedForm: undefined,
    attachForm:
      function(object, targetUrl, table, formId,  colspan, rowspan, isAjax){
        if(colspan == undefined) colspan = 2;
        if(rowspan == undefined) rowspan = 3;
        if(formId == undefined) formId = 0;
        if(isAjax == undefined) isAjax = true;
        if(App.Table.extraContent[table] == undefined){
          App.Table.lastAttachedForm = {
            ob: object,
            targetUrl: targetUrl,
            table: table,
            formId: formId,
            colspan: colspan,
            rowspan: rowspan,
            isAjax: isAjax
          };
          App.Table.extraContent[table] = true;
          var addTr = $(object).closest('tr');
          App.Table.standardContent = addTr;
          $(addTr).fadeOut('200', function(){
            var baseTr = $(addTr).prev('tr');
            var counter = $(baseTr).index() + 1;
            function setContent(t)
            {
              var element = App.Tools.removeMarkup(t, 'tr');
              var formTag = element.shift();
              var formRest = '';
              if(formTag.match(/</g).length > 1){
                start = formTag.indexOf('input');
                formRest = formTag.slice(start-1);
                formTag = formTag.slice(0, start-1);
                $(table).wrap(formTag);
                $(table).append(formRest);
              }
              else{
                $(table).wrap(formTag);
              }
              
              var retString = '';
              
              for(var i in element)
                {
                  if(i == 0 || element.length == 1)
                    {
                      retString += '<tr id="extra">' + element[i] + '\
        <td colspan="'+ colspan +'" rowspan="'+ rowspan +'">\n\
          <img src="/images/icons/save.png" class="middle" width="18" height="18"/>  \n\
          <a onclick="App.Form.submit(\''+ formId +'\''+(isAjax?',\''+isAjax+'\'':'')+')" class="middle">Zapisz</a>';
                      if(formId == 'updateItem'){
                        retString += '\
          <img src="/images/icons/save.png" class="middle" width="18" height="18"/>  \n\
          <a onclick="App.Form.switchAndSubmit(\''+ formId +'\''+(isAjax?',\''+isAjax+'\'':'')+')" class="middle">Zapisz nowy</a>';
                      }
                      retString += '\
          <img src="/images/icons/abort.png" class="middle" width="18" height="18"/>  \n\
          <a onclick="App.Table.detachForm(\''+ table +'\', \'tr\', \'#extra\')" class="middle">Anuluj</a>\n\
        </td></tr>'; 
                    }
                  else retString += '<tr id="extra">' + element[i]+ '</tr>';
                }
              $(retString).insertAfter(baseTr).hide().fadeIn('200');
              var width = $(table).width() + 50;
              var height = $(table).height() + 100;
              window.resizeTo(width, height);
            }
            App.ajaxRequest(targetUrl, undefined, setContent);
          });
        }
      },
    detachForm:
      function(table, element, selector){
        if(App.Table.extraContent[table]){
          delete(App.Table.extraContent[table]);
          $('table'+table+' '+element+selector).fadeOut('200', function(){
            $('table'+table+' '+element).remove(selector);
            if(App.Table.standardContent == undefined) $('table'+table+' '+'tr#add').fadeIn('200', function(){});
            else if(App.Table.standardContent != undefined) App.Table.standardContent.fadeIn('200', function(){});
          });
        }
      },
    refreshLastForm:
      function(){
        element = "tr";
        selector = "#extra";
        
        object = App.Table.lastAttachedForm.ob;
        targetUrl = App.Table.lastAttachedForm.targetUrl;
        table = App.Table.lastAttachedForm.table;
        formId = App.Table.lastAttachedForm.formId;
        colspan = App.Table.lastAttachedForm.colspan;
        rowspan = App.Table.lastAttachedForm.rowspan;
        isAjax = App.Table.lastAttachedForm.isAjax;
        
        
        App.Form.store(formId);
        App.Table.detachForm(table, element, selector);
        window.setTimeout(function(){
          App.Table.attachForm(object, targetUrl, table, formId, colspan, rowspan, isAjax);
        }, 200);
        window.setTimeout(function(){
          App.Form.restore(formId);
        }, 2000);
      },
    toggleCheckAll:
      function(table){
        if(!App.Table.checkedAll[table]){
          $('table'+table).find('input[type=checkbox]').each(function(){
            $(this).attr('checked', 'true');
          });
          App.Table.checkedAll[table] = true;
        }
        else{
          $('table'+table).find('input[type=checkbox]').each(function(){
            $(this).removeAttr('checked');
          });
          App.Table.checkedAll[table] = false;
        }
      }
      ,
    addDemandRow:
      function(element, eraseTrigger, wz){
        var row = $(element).closest('tr').next('tr');
        var selectValue = $(row).children('td').children('select').prop('value');
        var newRow = row.clone();
        newId = "items_list_values_"+ ($('tr[id]').length + 1);
        var onchange = '';
        if(wz == undefined) onchange = "var value = $(this).prop('value'); App.Form.updateAttribute('#items_list_values_"+($('tr[id]').length + 1)+"', 'name', 'production_demand[items_list_values]['+value+']')";
        else onchange = "var value = $(this).prop('value'); App.Form.updateAttribute('#items_list_values_"+($('tr[id]').length + 1)+"', 'name', 'wz[items_list_values]['+value+']')";
        // aktualizacja wywołania funkcji
        $(newRow).children('td').children('select[onchange]').attr('onchange', onchange);
        // usuń <option> który jest już wykorzystany
        //$(newRow).children('td').children('select[onchange]').children('option[value='+selectValue+']').remove();
        // nadanie nowej wartości potrzebnej do wywołania funkcji
        nextSelectValue = $(newRow).children('td').children('select[onchange]').prop('value');
        if(wz == undefined) $(newRow).children('td').children('input[id]').prop('id', newId).prop('name', 'production_demand[items_list_values]['+nextSelectValue+']').prop('value', '');
        else $(newRow).children('td').children('input[id]').prop('id', newId).prop('name', 'wz[items_list_values]['+nextSelectValue+']').prop('value', '');
        // jeśli elementy zawierają <span id=error> to je usuń
        if($(newRow).children('td').children('input[id]').next('span[id=error]')) $(newRow).children('td').children('input[id]').next('span[id=error]').remove();
        // nadaj nowe id <tr>
        $(newRow).prop('id', 'item_'+($('tr[id]').length + 1));
        if($(newRow).children('td').children('select[onchange]').children().length > 0){
          $('tr[id]').last().after(newRow);
          if($(newRow).prop('id') != "item_1"){
            $(newRow).children('td').last().html('<img src="/images/icons/delete.png" width="16" height="16" class="middle" onclick="App.Table.removeRow(\''+$(row).closest('table').prop('id')+'\',\''+$(newRow).prop('id')+'\')" />');
          }
          if(eraseTrigger) $(element).remove();
        }
      },
    removeRow:
      function(tableId, id){
        $('#'+id).remove();
        rows = $('#'+tableId+' tr[id!="item_1"][id*=item]');
        if(rows.length != 0){
          for(var i = 0; i < rows.length; i++){
            $(rows[i]).prop('id', 'item_'+(i+2));
            $(rows[i]).children('td').last().children('img').attr('onclick', 'App.Table.removeRow(\''+$('#'+tableId).prop('id')+'\',\'item_'+(i+2)+'\')');
            App.Table.updateRow($(rows[i]), i+2);
          }
        }
      },
    updateRow:
      function(row, newIndex){
        var select = row.children('td').children('select');
        var input = row.children('td').children('input');
        var onchange = '';
        if($("select[name*=production_demand]").length){
          onchange = "var value = $(this).prop('value'); App.Form.updateAttribute('#items_list_values_"+ newIndex +"', 'name', 'production_demand[items_list_values]['+value+']')";
        }
        else if($("select[name*=wz]").length){
          onchange = "var value = $(this).prop('value'); App.Form.updateAttribute('#items_list_values_"+ newIndex +"', 'name', 'wz[items_list_values]['+value+']')";
        }
        $(select).attr('onchange', onchange);
        $(input).attr('id', 'items_list_values_'+ newIndex);
      }
  },
  // build-in objects
  Tools: {
    removeMarkup:
      function(formSource, separator){
        var stringArray = formSource.split('<'+ separator +'>');
        var returnArray = new Array();
        for(var i in stringArray){
          if(stringArray[i] != '')
            {
              returnArray.push(stringArray[i].replace('<\/'+ separator +'>\n', ''));
            }
        }
        return returnArray;
      },
    removeErrors:
      function(text){
        lines = text.split('\n');
        var start = 0;
        var end = lines.length;
        var good = new Array();
        if(lines.length != 1)
        {
          for(var i = 0; i < lines.length; i++)
          {
            if(lines[i] == "") start = i + 1;
          }
          return (lines.slice(start+1, end)).join("");
        }
        else return lines.join("");
      },
    parseParams:
      function(content, lineSeparator, paramSeparator){
        if(lineSeparator == undefined) lineSeparator = '#';
        if(paramSeparator == undefined) paramSeparator = '@';
        if(typeof content == "string"){
          content = App.Tools.removeErrors(content);
          base = content.split(lineSeparator);
          if(base.length){
            params = function(){
              this.table = new Array();
              this.addParam = function(key, value){
                this.table[key] = value;
              }
            }
            p = new params();
            for(i in base){
              if(base[i] != ''){
                param = base[i].split(paramSeparator);
                p.addParam(param[0], param[1]);
              }
            }
            return(p.table);
          }
          else return false;
        }
        else return false;
      },
    getSourceOpener:
    function(windowObject){
      if(windowObject.opener != null){
        tmpWindow = windowObject.opener;
        console.log(windowObject.name);
        tmpOpener = App.Tools.getSourceOpener(tmpWindow);
        return tmpOpener;
      }
      else return windowObject;
      //return windowObject.opener;
    }
  }
}
